package example.hash表;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Demo1 {

    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            //另一半
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }

            //数值元素-数组元素的下标
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }


    public static int[] twoSum(int[] nums, int target) {
        //0-2   1-7
        HashMap<Integer, Integer> table = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int res = target - nums[i];
            if (table.get(nums[i]) == null) {
                table.put(i, res);
            } else if (table.get(nums[i]) == res) {

                return new int[]{i, table.get(nums[i])};
            }
        }
        return new int[]{-1, -1};
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[]{2, 7, 11, 15}, 9)));
    }
}
